<?php

namespace app\admin\controller\retrieval;

use app\admin\model\department\Department as DepartmentModel;
use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Tree;

/**
 * 成品检索管理
 *
 * @icon fa fa-user
 */
class Retrieval extends Backend
{

    protected $relationSearch = true;

    /**
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\department\Article;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
			$wheres = ['publish' => 1];
			if (!$this->auth->isSuperAdmin()) {
				$wheres = $this->_getAuthIds();
				if (empty($wheres)) {
					$result = array("total" => 0, "rows" => []);
					return json($result);
				}
			}

            //检索附件中的文本内容
            $fileContent = $this->request->param("file_content", '');
            if (!empty($fileContent)) {
                $modelArticleFile = new \app\admin\model\department\ArticleFile;
                $articleFileWhere = [
                    "file_content" => ['like', "%{$fileContent}%"]
                ];
                $articleFileIds = $modelArticleFile->where($articleFileWhere)->column("article_id");
                $wheres["article.id"] = ["in", $articleFileIds];
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['createuser', 'grouping', "department", "position", "type"])
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->paginate($limit);
            $this->tree = Tree::instance();
            $this->tree->init(DepartmentModel::allDepartment(), 'parent_id');
            foreach ($list as $k => $v) {
                $departmentList = $this->tree->getParentsIds($v['department_id'], true);
                $departmentIds = DepartmentModel::whereIn('id', $departmentList)->order("id asc")->column("name");
                $v['department_name'] = implode("", $departmentIds);
                $v->hidden(['createuser.password', 'createuser.salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    private function _getAuthIds1(): array
    {
        $ids = [];
        $model = new \app\admin\model\department\ArticleUser;
        $bandUserWhere = [
            "user_id" => $this->auth->id,
            "publish" => 1
        ];
        $exits = $model->with("article")->where($bandUserWhere)->column("article_id");
        if (!empty($exits)) {
            $ids = array_merge($exits, $ids);
        }

        $wheres = ['publish' => 1];
        $model = new \app\admin\model\department\ArticlePublish;
        $where = array(
            "type" => 1,
        );
        $departmentIds = $model->where($where)->column("with_id");
        if (!empty($departmentIds)) {
            $wheres['department_id'] = ["in", $departmentIds];
            $departmentIds = $this->model->where($wheres)->column("id");
            $ids = array_merge($departmentIds, $ids);
        }
        $where = array(
            "type" => 2,
        );
        $positionIds = $model->where($where)->column("with_id");
        if (!empty($positionIds)) {
            $wheres['position_id'] = ["in", $positionIds];
			//dump($wheres);die;

            $positionIds = $this->model->where($wheres)->column("id");
            $ids = array_merge($positionIds, $ids);
        }
		//dump($wheres);die;
		//$tempIds = $this->model->where($wheres)->column("id");
		//$ids = array_merge($tempIds, $ids);
		//dump($ids);die;

//        $where = array(
//            "type" => 3,
//        );
//        $typeIds = $model->where($where)->column("with_id");
//        if (!empty($typeIds)) {
//            $wheres['type_id'] = ["in", $typeIds];
//            $typeIds = $this->model->where($wheres)->column("id");
//            $ids = array_merge($typeIds, $ids);
//        }
//        if (!empty($row['grouping_id'])) {
//            $groupingIds = $this->model->where(['grouping_id' => ["in", $row['grouping_id']]])->column("id");
//            $ids = array_merge($groupingIds, $ids);
//        }
        $where = [];
        $ids = array_unique($ids);
        if (!empty($ids)) {
            $where["article.id"] = ["in", $ids];
        }
        return $where;
    }
    private function _getAuthIds(): array
    {
//        $ids = $this->model->where(['publish' => 1])->column("id");
        $ids = [];
        $wheres = ['publish' => 1];
        $model = new \app\admin\model\Admin;
        $row = $model->get($this->auth->id);
        $model = new \app\admin\model\department\ArticlePublish;
		$departmentIds = [];
		//dump($row['department_id']);
        if (!empty($row['department_id'])) {
            $tree = Tree::instance();
            $tree->init(DepartmentModel::allDepartment(), 'parent_id');
            $departmentList = $tree->getChildrenIds($row['department_id'], true);
            $wheres['department_id'] = ["in", $departmentList];
			$where = array(
				"type" => 1,
				"with_id" => ["in", $departmentList]
			);
			$ids = $model->where($where)->column("article_id");
            //$ids = $this->model->where($wheres)->column("id");
            //$ids = array_merge($departmentIds, $ids);
        }
		//dump($ids);
		//dump($row['position_id']);
        if (!empty($row['position_id'])) {
			$where = array(
				"type" => 2,
				"with_id" => $row['position_id']
			);
			$positionIds = $model->where($where)->column("article_id");
            //$positionIds = $this->model->where(['position_id' => ["in", $row['position_id']]])->column("id");
			if (!empty($ids)) {
				if (!empty($positionIds)) {
					$ids = array_intersect($ids, $positionIds);
				}
			} else {
				$ids = $positionIds;
			}
            //$ids = array_merge($positionIds, $ids);
        }
		
        if (!empty($row['type_id'])) {
			$where = array(
				"type" => 3,
				"with_id" => $row['type_id']
			);
			$typeIds = $model->where($where)->column("article_id");
			if (!empty($ids)) {
				if (!empty($typeIds)) {
					$ids = array_intersect($ids, $typeIds);
				}
			} else {
				$ids = $typeIds;
			}
        }
		
		
		//dump($ids);die;
        //if (!empty($row['type_id'])) {
        //    $typeIds = $this->model->where(['type_id' => ["in", $row['type_id']]])->column("id");
        //    $ids = array_merge($typeIds, $ids);
        //}
		//if (!empty($row['grouping_id'])) {
        //    $groupingIds = $this->model->where(['grouping_id' => ["in", $row['grouping_id']]])->column("id");
        //    $ids = array_merge($groupingIds, $ids);
        //}
        $where = [];
        $ids = array_unique($ids);
        if (!empty($ids)) {
            $where["article.id"] = ["in", $ids];
        }
        return $where;
    }


}
